const pageStack = getCurrentPages()

Page({
  onLoad(){
    const app = getApp()
    this.setData({...app.userProfile})
  },
  getUserNickname(event){
    console.log(event);
    this.updateNickname(event.detail.value)
  },
  async updateNickname(nickName){
    const {code} = await  wx.http.put('/userInfo',{nickName})
    if(code !== 10000) return wx.utils.toast('更新昵称失败')

    pageStack[0].setData({nickName})
    
    // 同步更新
    const app = getApp()
    app.userProfile.nickName = nickName
  },


  getUserAvatar(event){
    this.updateAvatar(event.detail.avatarUrl)
  },
  updateAvatar(avatar){
    wx.uploadFile({
      url: wx.http.baseURL + '/upload',
      filePath: avatar,
      name: 'file',
      header:{
        Authorization:'Bearer ' + getApp().token
      }, 
      FormData:{
        type:'avatar'
      },
      success:(res) =>{
        const data = JSON.parse(res.data)
        if(data.code !== 10000) return wx.utils.toast('上传失败')
        // 在我的页面渲染
        pageStack[0].setData({avatar:data.data.url})
        
        //在当前页面渲染头像
        this.setData({avatar:data.data.url})
        // 同步更新
        const app = getApp()
        app.userProfile.avatar = data.data.url
      }
    })
  }
})